package com.wannengbang.cloudleader.homepage;

import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.RecyclerView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.wannengbang.cloudleader.R;
import com.wannengbang.cloudleader.base.BaseActivity;
import com.wannengbang.cloudleader.base.DataCallBack;
import com.wannengbang.cloudleader.bean.QueryOrderBean;
import com.wannengbang.cloudleader.bean.QueryOrderListBean;
import com.wannengbang.cloudleader.homepage.adapter.TransQueryListAdapter;
import com.wannengbang.cloudleader.homepage.model.HomePageModelImpl;
import com.wannengbang.cloudleader.homepage.model.IHomePageModel;
import com.wannengbang.cloudleader.utils.DateTimeUtil;
import com.wannengbang.cloudleader.utils.Dp2Px;
import com.wannengbang.cloudleader.utils.NumberFormatUtils;
import com.wannengbang.cloudleader.utils.ToastUtil;
import com.wannengbang.cloudleader.widget.AppTitleBar;
import com.wannengbang.cloudleader.widget.MaterialHeader;
import com.wannengbang.cloudleader.widget.WrapContentLinearLayoutManager;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 交易查询
 */
public class TransactionQueryActivity extends BaseActivity implements OnRefreshLoadMoreListener {

    @BindView(R.id.title_bar)
    AppTitleBar titleBar;
    @BindView(R.id.tv_total_money1)
    TextView tvTotalMoney1;
    @BindView(R.id.edit_search)
    EditText editSearch;
    @BindView(R.id.view_cancel)
    View viewCancel;
    @BindView(R.id.ll_search)
    LinearLayout llSearch;
    @BindView(R.id.tv_search)
    TextView tvSearch;
    @BindView(R.id.tv_total_money2)
    TextView tvTotalMoney2;
    @BindView(R.id.tv_order_num)
    TextView tvOrderNum;
    @BindView(R.id.tv_single_price)
    TextView tvSinglePrice;
    @BindView(R.id.ll_no_data)
    LinearLayout llNoData;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.layout_title)
    LinearLayout layoutTitle;
    @BindView(R.id.nestedScrollView)
    NestedScrollView nestedScrollView;
    @BindView(R.id.tv_select_time)
    TextView tvSelectTime;
    @BindView(R.id.view_line)
    View viewLine;
    private IHomePageModel homePageModel;
    private String start_time;
    private String end_time;
    private int timeType = 1;
    private Calendar selectedDate;
    private TimePickerView pvCustomTime;
    private TextView tvStartTime;
    private TextView tvEndTime;

    private List<QueryOrderListBean.DataBean.ItemListBean> beanList;
    private TransQueryListAdapter listAdapter;
    private int page = 1;
    private String keyword = "";
    private String cycleType;
    private String param;
    private boolean isSetBar;
    private String trans_type;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_transaction_query);
        ButterKnife.bind(this);
        getImmersionBar().statusBarDarkFont(false).statusBarDarkFont(false, 0.2f).init();
        initView();
        initData();
    }

    private void initView() {
        cycleType = getIntent().getStringExtra("cycleType");
        param = getIntent().getStringExtra("param");
        trans_type = getIntent().getStringExtra("trans_type");
        if (TextUtils.isEmpty(trans_type)) {
            trans_type = "";
        }
        refreshLayout.setRefreshHeader(new MaterialHeader(mActivity));//设置Header
        refreshLayout.setRefreshFooter(new ClassicsFooter(mActivity));//设置Footer
        refreshLayout.setOnRefreshLoadMoreListener(this);

        editSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    if (!TextUtils.isEmpty(keyword)) {
                        refreshData();
                    }
                    return true;
                }
                return false;
            }
        });
        editSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                keyword = editSearch.getText().toString().trim();
                if (!TextUtils.isEmpty(keyword)) {
                    viewCancel.setVisibility(View.VISIBLE);
                } else {
                    viewCancel.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        titleBar.setRightClickListener(() -> {
            showActivity(AddAgentActivity.class);
        });

        int height = (int) Dp2Px.dp2Px(181);
        nestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                if (scrollY <= 0) {   //设置标题的背景颜色
                    layoutTitle.setBackgroundColor(Color.argb((int) 0, 255, 255, 255));
                    viewLine.setBackgroundColor(Color.argb((int) 0, 243, 243, 243));
                    titleBar.setTitleColor(getResources().getColor(R.color.white));
                    titleBar.setLeftIcon(R.mipmap.ic_back_white);
                    getImmersionBar().statusBarDarkFont(false).statusBarDarkFont(false, 0.2f).init();
                    isSetBar = false;
                } else if (scrollY > 0 && scrollY <= height) { //滑动距离小于banner图的高度时，设置背景和字体颜色颜色透明度渐变
                    float scale = (float) scrollY / height;
                    float alpha = (255 * scale);
                    layoutTitle.setBackgroundColor(Color.argb((int) alpha, 255, 255, 255));
                    viewLine.setBackgroundColor(Color.argb((int) alpha, 243, 243, 243));
                } else {    //滑动到banner下面设置普通颜色
                    if (!isSetBar) {
                        layoutTitle.setBackgroundColor(Color.argb((int) 255, 255, 255, 255));
                        viewLine.setBackgroundColor(Color.argb((int) 255, 243, 243, 243));
                        titleBar.setTitleColor(getResources().getColor(R.color.text_color_2));
                        titleBar.setLeftIcon(R.mipmap.ic_back_black);
                        getImmersionBar().statusBarDarkFont(true).statusBarDarkFont(true, 0.2f).init();
                        isSetBar = true;
                    }
                }
            }
        });
    }


    public void initData() {
        homePageModel = new HomePageModelImpl();
        start_time = DateTimeUtil.format(new Date());
        end_time = DateTimeUtil.format(new Date());
        selectedDate = Calendar.getInstance();

        if ("all".equals(cycleType)) {
            start_time = param.replace(".", "-");
            end_time = DateTimeUtil.format(new Date());
        } else if ("date".equals(cycleType)) {
            start_time = param.replace(".", "-");
            end_time = start_time;
        } else if ("month".equals(cycleType)) {
            start_time = DateTimeUtil.getFirstDayOfMonth(param.replace(".", "-"));
            end_time = DateTimeUtil.getLastDayOfMonth(param.replace(".", "-"));
        }
        tvSelectTime.setText(start_time + " 至 " + end_time);

        beanList = new ArrayList<>();
        listAdapter = new TransQueryListAdapter(beanList);
        recyclerView.setLayoutManager(new WrapContentLinearLayoutManager(mActivity));
        recyclerView.setAdapter(listAdapter);

        requestDailyNew();
        requestData();
    }

    public void requestDailyNew() {
        homePageModel.requestDailyNew(trans_type, start_time, end_time, new DataCallBack<QueryOrderBean>() {
            @Override
            public void onSuccessful(QueryOrderBean bean) {
                String money = NumberFormatUtils.formatTwoDecimal(bean.getData().getTotal_order_fee() / 100);
                tvTotalMoney1.setText(money);
                tvTotalMoney2.setText(money);
                tvOrderNum.setText(bean.getData().getTotal_order_count() + "");
                if (bean.getData().getTotal_order_count() > 0) {
                    String singlePrice = NumberFormatUtils.formatTwoDecimal(bean.getData().getTotal_order_fee() / 100 / bean.getData().getTotal_order_count());
                    tvSinglePrice.setText(singlePrice);
                } else {
                    tvSinglePrice.setText("0.00");
                }

            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }


    public void requestData() {
        homePageModel.requestDailyNewList(page, trans_type, "1", "1", keyword, start_time, end_time, new DataCallBack<QueryOrderListBean>() {
            @Override
            public void onSuccessful(QueryOrderListBean bean) {
                if (bean.getData().getItemList() != null && bean.getData().getItemList().size() > 0) {
                    beanList.addAll(bean.getData().getItemList());
                    if (page == 1) {
                        refreshLayout.finishRefresh();
                    } else {
                        refreshLayout.finishLoadMore();
                    }
                } else {
                    if (page != 1) {
                        refreshLayout.finishLoadMoreWithNoMoreData();
                    } else {
                        refreshLayout.finishRefresh();
                    }
                }
                if (beanList.size() > 0) {
                    llNoData.setVisibility(View.GONE);
                } else {
                    llNoData.setVisibility(View.VISIBLE);
                }
                listAdapter.notifyDataSetChanged();

            }

            @Override
            public void onFailed(String msg, String code) {
                listAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        page++;
        requestData();
        refreshLayout.finishLoadMore(30000);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        refreshData();
    }

    public void refreshData() {
        page = 1;
        beanList.clear();
        requestData();
        refreshLayout.finishRefresh(30000);
        requestDailyNew();
    }


    @OnClick({R.id.tv_select_time, R.id.view_cancel, R.id.tv_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_select_time:
                selectTime();
                break;
            case R.id.view_cancel:
                editSearch.setText("");
                keyword = "";
                refreshData();
                break;
            case R.id.tv_search:
                if (TextUtils.isEmpty(keyword)) {
                    ToastUtil.showShort("请输入搜索内容");
                    return;
                }
                refreshData();
                break;
        }
    }

    public void selectTime() {
        timeType = 1;
        String[] times = tvSelectTime.getText().toString().split(" 至 ");
        if (times != null) {
            start_time = times[0];
            end_time = times[1];
        }
        selectedDate.setTime(DateTimeUtil.parse(start_time));
        //这里可以更改参数，有好多类型
        Calendar startDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();
        startDate.set(1900, 0, 1);
        endDate.set(2099, 11, 31);
        pvCustomTime = new TimePickerBuilder(mActivity, (date, v) -> {
            tvSelectTime.setText(start_time + " 至 " + end_time);
            refreshData();

        }).setType(new boolean[]{true, true, true, false, false, false})
                .setTimeSelectChangeListener(date -> {
                    if (timeType == 1) {
                        start_time = DateTimeUtil.format(date);
                        if (tvStartTime != null) {
                            tvStartTime.setText(start_time);
                        }
                    } else {
                        end_time = DateTimeUtil.format(date);
                        if (tvEndTime != null) {
                            tvEndTime.setText(end_time);
                        }
                    }
                })
                .setLayoutRes(R.layout.pickerview_custom_time, new CustomListener() {

                    @Override
                    public void customLayout(View v) {
                        TextView tvSubmit = v.findViewById(R.id.tv_finish);
                        TextView ivCancel = v.findViewById(R.id.tv_cancel);
                        tvStartTime = v.findViewById(R.id.tv_start_time);
                        tvEndTime = v.findViewById(R.id.tv_end_time);
                        View viewLine1 = v.findViewById(R.id.view_line1);
                        View viewLine2 = v.findViewById(R.id.view_line2);
                        LinearLayout llStartTime = v.findViewById(R.id.ll_start_time);
                        LinearLayout llEndTime = v.findViewById(R.id.ll_end_time);

                        tvStartTime.setText(start_time);
                        tvEndTime.setText(end_time);

                        llStartTime.setOnClickListener(v1 -> {
                            timeType = 1;
                            tvStartTime.setTextColor(mActivity.getResources().getColor(R.color.theme_color));
                            viewLine1.setBackgroundColor(mActivity.getResources().getColor(R.color.theme_color));
                            tvEndTime.setTextColor(mActivity.getResources().getColor(R.color.text_color_2));
                            viewLine2.setBackgroundColor(mActivity.getResources().getColor(R.color.text_color_2));

                            selectedDate.setTime(DateTimeUtil.parse(tvStartTime.getText().toString()));
                            pvCustomTime.setDate(selectedDate);


                        });
                        llEndTime.setOnClickListener(v1 -> {
                            timeType = 2;
                            tvStartTime.setTextColor(mActivity.getResources().getColor(R.color.text_color_2));
                            viewLine1.setBackgroundColor(mActivity.getResources().getColor(R.color.text_color_2));
                            tvEndTime.setTextColor(mActivity.getResources().getColor(R.color.theme_color));
                            viewLine2.setBackgroundColor(mActivity.getResources().getColor(R.color.theme_color));

                            selectedDate.setTime(DateTimeUtil.parse(tvEndTime.getText().toString()));
                            pvCustomTime.setDate(selectedDate);


                        });

                        tvSubmit.setOnClickListener(v1 -> {
                            pvCustomTime.returnData();
                            pvCustomTime.dismiss();
                        });
                        ivCancel.setOnClickListener(v1 -> {
                            pvCustomTime.dismiss();
                        });
                    }
                })
                .setSubmitColor(getResources().getColor(R.color.text_color_2))//确定按钮文字颜色
                .setSubCalSize(14)
                .setCancelColor(getResources().getColor(R.color.text_color_2))//取消按钮文字颜色
                .setTitleBgColor(getResources().getColor(R.color.white))
                .setDividerColor(getResources().getColor(R.color.line_color_gray))
                .setTextColorCenter(getResources().getColor(R.color.text_color_2))
                .setContentTextSize(15)
                .setLineSpacingMultiplier(2f)
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .isDialog(true) //默认设置false ，内部实现将DecorView 作为它的父控件。
                .build();

        Dialog mDialog = pvCustomTime.getDialog();
        if (mDialog != null) {
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM);

            params.leftMargin = 0;
            params.rightMargin = 0;
            pvCustomTime.getDialogContainerLayout().setLayoutParams(params);

            Window window = mDialog.getWindow();
            if (window != null) {
                window.setWindowAnimations(R.style.picker_view_slide_anim);//修改动画样式
                window.getDecorView().setPadding(0, 0, 0, 0);
                WindowManager.LayoutParams lp = window.getAttributes();
                lp.width = WindowManager.LayoutParams.MATCH_PARENT;
                lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
                lp.gravity = Gravity.BOTTOM;
            }
        }
        pvCustomTime.show();
    }
}
